package com.example.asynctaskdemo;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class CounterActivity extends AppCompatActivity {

    private AsyncTask progressDemoAt_1, progressDemoAt_2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_counter);
        findView();
        initView();
        initData();
    }

    private void findView() {

    }

    private void initView() {

    }

    private void initData() {
        progressDemoAt_1 = new ProgressDemoAt_1();
        progressDemoAt_1.execute();
        progressDemoAt_2 = new ProgressDemoAt_2();
        progressDemoAt_2.execute();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (progressDemoAt_1 != null && !progressDemoAt_1.isCancelled()) {
            progressDemoAt_1.cancel(true);
        }
        if (progressDemoAt_2 != null && !progressDemoAt_2.isCancelled()) {
            progressDemoAt_2.cancel(true);
        }
    }

    static class ProgressDemoAt_1 extends AsyncTask {
        private final String TAG = getClass().getSimpleName();
        private int count;

        @Override
        protected Object doInBackground(Object[] objects) {
            while (count < 5 && !isCancelled()) {
                try {
                    count++;
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {
                }
                Log.d(TAG, "ProgressDemoAt_1 count value: " + count);
                publishProgress();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Object[] values) {
            if (count >= 3) {
                cancel(true);
                Log.d(TAG, "ProgressDemoAt_1 canceled");
            }
        }
    }

    static class ProgressDemoAt_2 extends AsyncTask {
        private final String TAG = getClass().getSimpleName();
        private int count;

        @Override
        protected Object doInBackground(Object[] objects) {
            while (count < 5 && !isCancelled()) {
                try {
                    count++;
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {
                }
                Log.d(TAG, "ProgressDemoAt_2 count value: " + count);
                publishProgress();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Object[] values) {
            if (count >= 3) {
                cancel(true);
                Log.d(TAG, "ProgressDemoAt_2 canceled");
            }
        }
    }
}
